//
//  VVYPayManager.m
//  viviyoo
//
//  Created by viviyoo on 15/12/10.
//  Copyright © 2015年 viviyoo. All rights reserved.
//

#import "VVYPayManager.h"
#import "LYAlipayModel.h"
#import "LYWXPayModel.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "WXApiManager.h"
#import "UPPaymentControl.h"

//支付宝支付状态
typedef enum : NSUInteger {
    AlipayResultTypeSuccess = 9000,
    AlipayResultTypeProcess = 8000,
    AlipayResultTypeFailure = 4000,
    AlipayResultTypeCancel = 6001,
    AlipayResultTypeNetConnectError = 6002
} AlipayResultType;


@interface VVYPayManager ()<WXApiManagerDelegate>

@property (nonatomic, copy) payBlock success;

@property (nonatomic, copy) PayFailureBlock failure;

@end


@implementation VVYPayManager
static id _instance;

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    @synchronized(self) {
        if (_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    }
    return _instance;
}

+ (instancetype)sharedManager
{
    @synchronized(self) {
        if (_instance == nil) {
            _instance = [[self alloc] init];
        }
    }
    return _instance;
}

- (id)copyWithZone:(NSZone *)zone
{
    return _instance;
}

- (void)payWithOrderNum:(NSString *)orderNum price:(NSString *)price andPayType:(PayType) type success:(payBlock) success failure:(PayFailureBlock) failure{
    
    _success = success;
    _failure = failure;

    switch (type) {
        //没选择
        case PayTypeUPPay:
            [self UPPayWithOrderNum:orderNum price:price];
            break;
        //支付宝
        case PayTypeAlipay:
            [self AlipayWithOrderNum:orderNum price:price];
            break;
            
        //微信支付
        case PayTypeWeixinPay:
            [self WeixinWithOrderNum:orderNum price:price];
            break;
            
        default:
            break;
    }
    

}

#pragma mark - 参数配置

/**
 *  银联支付参数配置
 */
- (void)UPPayWithOrderNum:(NSString *)orderNum price:(NSString *)price{


    [MBProgressHUD showMessage:nil];
    [LYRequestTool getPayUnionpayWithToken:LYToken order_sn:orderNum success:^(NSString *tn) {
        
        [MBProgressHUD hideHUD];
        [self startUPPayWithTN:tn];
        
    } failure:^(NSString *code, NSString *message) {
        [MBProgressHUD hideHUD];
    }];

}

/**
 *  支付宝配置参数
 */
- (void)AlipayWithOrderNum:(NSString *)orderNum price:(NSString *)price{
    
    
    [MBProgressHUD showMessage:nil];
    
    [LYRequestTool getAlipaySignyWithToken:LYToken order_sn:orderNum success:^(LYAlipayModel *model) {
        [MBProgressHUD hideHUD];
        [self startAliPayWithPayStr:[model description]];
        
    } failure:^(NSString *code, NSString *message) {
        
        [MBProgressHUD hideHUD];
        [MBProgressHUD showOnlyText:message];
        
    }];
}


/**
 *  微信支付配置参数
 */
- (void)WeixinWithOrderNum:(NSString *)orderNum price:(NSString *)price{
    
    
    [MBProgressHUD showMessage:nil];
    [LYRequestTool getWeChatWithToken:LYToken order_sn:orderNum success:^(LYWXPayModel *model) {
        
        [MBProgressHUD hideHUD];
        
        [self startWeixinPayWithOrder:model];
        
    } failure:^(NSString *code, NSString *message) {
        
        [MBProgressHUD hideHUD];
        [MBProgressHUD showOnlyText:message];
    }];
    
}

#pragma mark - 调起
/**
 *  银联
 */
- (void)startUPPayWithTN:(NSString *)TN{


    [[UPPaymentControl defaultControl] startPay:TN fromScheme:@"LYUPPay" mode:@"01" viewController:[UIApplication sharedApplication].keyWindow.rootViewController];

}

/**
 *  调起支付宝支付
 */
- (void)startAliPayWithPayStr:(NSString *)orderStr{

    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"LYAlipay";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = orderStr;
    NSLog(@"------%@",orderStr);
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
//    NSString *orderString = nil;
//    if (order.sign != nil) {
//        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
//                       orderSpec, order.sign, order.sign_type];

        [[AlipaySDK defaultService] payOrder:orderSpec fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            
            
                        //NSlog(@"orderStr = %@",resultDic);
            AlipayResultType resultCode = (AlipayResultType)[resultDic[@"resultStatus"] integerValue];
//            NSString *memo = resultDic[@"memo"];
            
            switch (resultCode) {
                    //支付成功
                case AlipayResultTypeSuccess:
                    if(_success){
                        _success();
                    }
                    break;
                    //支付失败
                case AlipayResultTypeFailure:
                    if (_failure) {
                        _failure(@"支付失败");
                    }
                    break;
                    //取消支付
                case AlipayResultTypeCancel:
                    if (_failure) {
                        _failure(@"支付取消");
                    }
                    break;
                    //网络连接失败
                case AlipayResultTypeNetConnectError:
                    if (_failure) {
                        _failure(@"支付失败");
                    }
                    break;
                    //订单处理中
                case AlipayResultTypeProcess:
                    if (_failure) {
                        _failure(@"等待支付");
                    }
                    break;
                    
                default:
                    break;
            }
            
        }];
//    }
    
}


/**
 *  调起微信支付
 */
- (void)startWeixinPayWithOrder:(LYWXPayModel *)order{

    PayReq *request = [[PayReq alloc] init];
    request.partnerId = order.partnerid;
    request.prepayId = order.prepayid;
    request.package = order.package_value;
    request.nonceStr = order.noncestr;
    request.timeStamp = (UInt32)order.timestamp;
    request.sign = order.sign;
    [WXApi sendReq:request];

}

#pragma mark - 微信支付代理
/**
 *  微信支付回调
 */
- (void)managerDidFinshPayWithResult:(int)result{

    switch (result) {
            //支付成功
        case WXSuccess:
            if (_success) {
                _success();
            }
            break;
            //支付失败
        case WXErrCodeCommon:
            if (_failure) {
                _failure(@"支付失败");
            }
            break;
            //支付取消
        case WXErrCodeUserCancel:
            if (_failure) {
                _failure(@"支付取消");
            }
            break;
            
        default:
            break;
    }

}

/**
 *  银联支付回调
 */
- (void)handleUPPayCallBackInfoCode:(NSString *)code data:(NSDictionary *)data{


    //结果code为成功时，先校验签名，校验成功后做后续处理
    if([code isEqualToString:@"success"]) {
        
        if (_success) {
            _success();
        }

        //
        //                    //判断签名数据是否存在
        //                    if(data == nil){
        //                        //如果没有签名数据，建议商户app后台查询交易结果
        //                        return;
        //                    }
        //
        //                    //数据从NSDictionary转换为NSString
        //                    NSData *signData = [NSJSONSerialization dataWithJSONObject:data
        //                                                                       options:0
        //                                                                         error:nil];
        //                    NSString *sign = [[NSString alloc] initWithData:signData encoding:NSUTF8StringEncoding];
        //
        //
        //
        //                    //验签证书同后台验签证书
        //                    //此处的verify，商户需送去商户后台做验签
        //                    if([self verify:sign]) {
        //                        //支付成功且验签成功，展示支付成功提示
        //                    }
        //                    else {
        //                        //验签失败，交易结果数据被篡改，商户app后台查询交易结果
        //                    }
    }
    else if([code isEqualToString:@"fail"]) {
        //交易失败
        if (_failure) {
            _failure(@"支付失败");
        }

    }
    else if([code isEqualToString:@"cancel"]) {
        //交易取消
        if (_failure) {
            _failure(@"支付取消");
        }

    }


}
@end
